package com.ucomm.talent.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.ucomm.talent.AppConfig;
import com.ucomm.talent.AppConstants;
import com.ucomm.talent.AppException;
import com.ucomm.talent.R;
import com.ucomm.talent.adapter.AdvAdapter;
import com.ucomm.talent.common.FileUtils;
import com.ucomm.talent.manager.SearchManager;
import com.ucomm.talent.widget.CustomProgressDialog;
import com.ucomm.talent.widget.FunctionView;
import com.ucomm.talent.widget.SearchBarView;

/**
 * 主页界面
 * Created with IntelliJ IDEA.
 * User: Vita Hao
 * Date: 13-5-21
 */
public class HomeActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener,IFunctionViewListener {
   // private ImageView ad = null;
    private EditText searchEditText;
    private LinearLayout searchLayout;

    private Spinner spinner;
    private Button btSearch;
    private EditText etSearch;

    private ImageView[] imageViews = null;
    private ImageView imageView = null;
    private ViewPager advPager = null;
    private AtomicInteger what = new AtomicInteger(0);
    private boolean isContinue = true;

    private FunctionView fv_featured_jobs;
    private FunctionView fv_job_offers;
    private FunctionView fv_hot_company;
    private FunctionView fv_job_fair;
    private FunctionView fv_talents;
    private FunctionView fv_resume;
    private FunctionView fv_news;
    private FunctionView fv_study;
    private CustomProgressDialog customProgressDialog;
    private SearchManager searchManager;
    
    Handler mHandler = new Handler(){
		public void handleMessage(Message msg) {
			int what = msg.what;
			switch (what) {
			case AppConstants.MsgStatus.MSG_ERROR:
                if (customProgressDialog != null && customProgressDialog.isShowing())
                    customProgressDialog.dismiss();
                ((AppException)msg.obj).makeToast(HomeActivity.this);
                break;
            case AppConstants.MsgStatus.MSG_SUCCUSS:
                if (customProgressDialog != null && customProgressDialog.isShowing())
                    customProgressDialog.dismiss();
                setContentView(R.layout.home_layout);
                initView();
        		FileUtils file = new FileUtils();
        		String path = "steeltalent"+File.separator;
        		if (file.isFileExist("steeltalent")){
        			if(file.isFileExist(path+"cityMap")){
        				AppConfig.cityMap = file.readMapFromSD("steeltalent", "cityMap");
        			}
        			if(file.isFileExist(path+"jobMap")){
        				AppConfig.jobMap = file.readMapFromSD("steeltalent", "jobMap");
        			}
        			if(file.isFileExist(path+"industryMap")){
        				AppConfig.industryMap = file.readMapFromSD("steeltalent", "industryMap");
        			}
        			if(file.isFileExist(path+"comMap")){
        				AppConfig.comMap = file.readMapFromSD("steeltalent", "comMap");
        			}
        			if(file.isFileExist(path+"userMap")){
        				AppConfig.userMap = file.readMapFromSD("steeltalent", "userMap");
        			}
        		}
        		
                break;
            case AppConstants.MsgStatus.MSG_LOADING:
                if (customProgressDialog != null && !customProgressDialog.isShowing())
                    customProgressDialog.show();
                break;
            default:
                break;
			}
			super.handleMessage(msg);
		}
	};
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        customProgressDialog = new CustomProgressDialog(this);
		searchManager = new SearchManager(this, mHandler);
		searchManager.searchDataFromNetwrok(AppConstants.CACHE);
    }

    private void initView() {
    	//推荐职位
        fv_featured_jobs = (FunctionView) findViewById(R.id.fv_featured_jobs);
        fv_featured_jobs.setViewListener(R.id.fv_featured_jobs,this);

        //招聘信息
        fv_job_offers = (FunctionView) findViewById(R.id.fv_job_offers);
        fv_job_offers.setViewListener(R.id.fv_job_offers, this);
        
        //热门企业
        fv_hot_company = (FunctionView) findViewById(R.id.fv_hot_company);
        fv_hot_company.setViewListener(R.id.fv_hot_company, this);
        //招聘会场
        fv_job_fair = (FunctionView) findViewById(R.id.fv_job_fair);
        fv_job_fair.setViewListener(R.id.fv_job_fair, this);
        
        //高级人才
        fv_talents = (FunctionView) findViewById(R.id.fv_talents);
        fv_talents.setViewListener(R.id.fv_talents, this);
        
        //应聘简历
        fv_resume = (FunctionView) findViewById(R.id.fv_resume);
        fv_resume.setViewListener(R.id.fv_resume, this);
        
        //行业资讯
        fv_news = (FunctionView) findViewById(R.id.fv_news);
        fv_news.setViewListener(R.id.fv_news, this);
        
        //培训课程
        fv_study = (FunctionView) findViewById(R.id.fv_study);
        fv_study.setViewListener(R.id.fv_study, this);
        
       // ad = (ImageView) findViewById(R.id.iv_ad);
//        searchEditText = (EditText) findViewById(R.id.et_search);
//        searchEditText.clearFocus();
//        spinner = (Spinner) findViewById(R.id.spinner_selecter);
//        searchLayout = (LinearLayout) findViewById(R.id.search_layout);
//        btSearch = (Button) searchLayout.findViewById(R.id.bt_search);
//        btSearch.setOnClickListener(this);
//
//        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.simple_spinner_item);
//        String level[] = getResources().getStringArray(R.array.search_content_list);//资源文件
//        for (int i = 0; i < level.length; i++) {
//            adapter.add(level[i]);
//        }
//        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        spinner.setAdapter(adapter);
        initViewPager();
    }

    private void initViewPager() {

        advPager = (ViewPager) findViewById(R.id.adv_pager);
        ViewGroup group = (ViewGroup) findViewById(R.id.viewGroup);

        //这里存放的是四张广告背景
        List<View> advPics = new ArrayList<View>();

        ImageView img1 = new ImageView(this);
        img1.setBackgroundResource(R.drawable.show_ad);
        advPics.add(img1);

        ImageView img2 = new ImageView(this);
        img2.setBackgroundResource(R.drawable.show_ad);
        advPics.add(img2);

        ImageView img3 = new ImageView(this);
        img3.setBackgroundResource(R.drawable.show_ad);
        advPics.add(img3);

        ImageView img4 = new ImageView(this);
        img4.setBackgroundResource(R.drawable.show_ad);
        advPics.add(img4);

        //对imageviews进行填充
        imageViews = new ImageView[advPics.size()];
        //小图标
        for (int i = 0; i < advPics.size(); i++) {
            imageView = new ImageView(this);
            imageView.setLayoutParams(new ViewGroup.LayoutParams(20, 20));
            imageView.setPadding(5, 5, 5, 5);
            imageViews[i] = imageView;
            if (i == 0) {
                imageViews[i].setBackgroundResource(R.drawable.banner_dian_focus);
            } else {
                imageViews[i].setBackgroundResource(R.drawable.banner_dian_blur);
            }
            group.addView(imageViews[i]);
        }

        advPager.setAdapter(new AdvAdapter(advPics));
        advPager.setOnPageChangeListener(new GuidePageChangeListener());
        advPager.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        isContinue = false;
                        break;
                    case MotionEvent.ACTION_UP:
                        isContinue = true;
                        break;
                    default:
                        isContinue = true;
                        break;
                }
                return false;
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (isContinue) {
                        viewHandler.sendEmptyMessage(what.get());
                        whatOption();
                    }
                }
            }

        }).start();
    }

    private void whatOption() {
        what.incrementAndGet();
        if (what.get() > imageViews.length - 1) {
            what.getAndAdd(-4);
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {

        }
    }

    private final Handler viewHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            advPager.setCurrentItem(msg.what);
            super.handleMessage(msg);
        }

    };


    private final class GuidePageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageSelected(int arg0) {
            what.getAndSet(arg0);
            for (int i = 0; i < imageViews.length; i++) {
                imageViews[arg0].setBackgroundResource(R.drawable.banner_dian_focus);
                if (arg0 != i) {
                    imageViews[i].setBackgroundResource(R.drawable.banner_dian_blur);
                }
            }

        }

    }


/*    private void initData(){
        functionList.add(new Function(getString(R.string.featured_jobs),R.drawable.home_bar_1));
        functionList.add(new Function(getString(R.string.job_offers),R.drawable.home_bar_1));
        functionList.add(new Function(getString(R.string.popular_businesses),R.drawable.home_bar_1));
        functionList.add(new Function(getString(R.string.recruitment_site),R.drawable.home_bar_1));
        functionList.add(new Function(getString(R.string.senior_personnel),R.drawable.home_bar_1));
        functionList.add(new Function(getString(R.string.training_courses),R.drawable.home_bar_1));
        functionList.add(new Function(getString(R.string.candidates_resume),R.drawable.home_bar_1));
        functionList.add(new Function(getString(R.string.news),R.drawable.home_bar_1));
    }*/

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    	
    }
    
    //搜索按钮监听
    @Override
    public void onClick(View view) {
        int id = view.getId();
        String url = null;
        String text = null;
        text = etSearch.getText().toString();
        if (id == btSearch.getId()) {       
        	if(text!=null){
        		if(text.equals("")){
        			Toast.makeText(this, "输入不能为空", Toast.LENGTH_SHORT).show();
        		}else{
        			//获取查找类型
        			if(spinner.getSelectedItem().toString().equals("找职位")){
        				//拼接url
        				url = AppConstants.JOB_SEARCH+text;
        				Intent i = new Intent();
        				i.putExtra("url", url);
        				i.setClass(this, JobOffers.class);
        				startActivity(i);
        			}else if (spinner.getSelectedItem().toString().equals("找人才")){
        				url = AppConstants.RESUME_SEARCH+text;
        				Intent i = new Intent();
        				i.putExtra("url", url);
        				i.setClass(this, ResumeActivity.class);
        				startActivity(i);
        			}
        		}
        	}
        }
    }


    @Override
    public void OnImgViewClickListener(int id, View view) {
        if(id == fv_featured_jobs.getId()){
            Intent i = new Intent(this,RecommendJobActivity.class);
            startActivity(i);
        }else if(id == fv_job_offers.getId()){
        	Intent i = new Intent(this,JobOffers.class);
        	startActivity(i);
        }else if(id ==fv_hot_company.getId()){
        	Intent i = new Intent(this,HotCompanyActivity.class);
        	startActivity(i);
        }else if(id == fv_job_fair.getId()){
        	Intent i = new Intent(this,JobFairActivity.class);
        	startActivity(i);
        }else if(id ==fv_talents.getId()){
        	Intent i = new Intent(this,TalentsActivity.class);
        	startActivity(i);
        }else if(id ==fv_resume.getId()){
        	Intent i = new Intent(this,ResumeActivity.class);
        	startActivity(i);
        }else if(id == fv_news.getId()){
        	Intent i = new Intent(this, NewsActivity.class);
        	startActivity(i);
        }else if(id == fv_study.getId()){
        	Intent i = new Intent(this,StudyActivity.class);
        	startActivity(i);
        }

    }




}
